package org.jeecg.modules.xmss.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ImportExcelUtil;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 意见督办关系表
 * @Author: jeecg-boot
 * @Date: 2020-09-18
 * @Version: V1.0
 */
@Api(tags = "用户操作")
@RestController
@RequestMapping("/xmss/xmssUser")
@Slf4j
public class XmssUserController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private BaseCommonService baseCommonService;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 管理员新建人大代表账号
     *
     * @param
     * @return
     */
    @AutoLog(value = " 管理员新建人大代表账号")
    @ApiOperation(value = "管理员新建人大代表账号", notes = "管理员新建人大代表账号")
    @PostMapping("/add")
    public Result<List<SysUser>> add(@RequestBody JSONObject jsonObject) {
        Result<List<SysUser>> result = new Result<List<SysUser>>();
        SysUser sysUser = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
        if (this.selectUser(sysUser.getUsername(), null).isEmpty()) {
            String salt = oConvertUtils.randomGen(8);
            String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), "123456", salt);
            LoginUser sysUsers = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            sysUser.setRelTenantIds(sysUsers.getRelTenantIds());
            sysUser.setSex(0);
            sysUser.setPhone(sysUser.getUsername());
            sysUser.setCreateBy(sysUsers.getUsername());
            sysUser.setSalt(salt);
            sysUser.setPassword(passwordEncode);
            sysUser.setDelFlag(0);
            sysUser.setStatus(1);
            sysUser.setActivitiSync(1);
            sysUser.setAvatar(sysUser.getAvatar());
            sysUser.setType(sysUser.getType());
            if(sysUser.getNickname()!=null && !"".equals(sysUser.getNickname())){
                sysUser.setNickname(sysUser.getNickname());
            }

            sysUserService.save(sysUser);
        } else {
            result.setMessage("用户名重复");
            result.setCode(500);
        }
        return result;
    }


    /**
     * 分页列表查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "人大代表账号-分页列表查询")
    @ApiOperation(value = "人大代表账号-分页列表查询", notes = "人大代表账号-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(@RequestParam(name = "realname", required = false) String realname,
                                   @RequestParam(name = "type", required = false) Integer type,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        SysUser sysUser = new SysUser();
        sysUser.setDelFlag(0);
        sysUser.setStatus(1);
        LoginUser sysUsers = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUsers.getUsername();
        if (!"admin".equals(username)) {
            sysUser.setRelTenantIds(sysUsers.getRelTenantIds());
            sysUser.setCreateBy(sysUsers.getUsername());
        }
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, req.getParameterMap());
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);

        //姓名关键词
        if (oConvertUtils.isNotEmpty(realname)) {
            queryWrapper.like("realname", realname);
        }
            //查询类型
        queryWrapper.eq("type", type);

        IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);
        SysUser getsysUser = new SysUser();
        pageList.getRecords().stream().forEach(e -> {
            getsysUser.setUsername(e.getCreateBy());
        });
        SysUser getsysUsers = sysUserRoleMapper.selectOnes(getsysUser.getUsername());
        pageList.getRecords().stream().forEach(e -> {
            e.setCreateBy(getsysUsers.getRealname());
        });
        return Result.OK(pageList);
    }


    /**
     * 编辑用户名
     *
     * @param
     * @return
     */
    @AutoLog(value = "人大代表账号-编辑")
    @ApiOperation(value = "人大代表账号-编辑", notes = "人大代表账号-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody JSONObject jsonObject) {
        SysUser sysUser = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
        SysUser sysUsers = new SysUser();
        sysUsers.setUsername(sysUser.getUsername());
        String salt = oConvertUtils.randomGen(8);
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), "123456", salt);
        sysUsers.setPassword(passwordEncode);
        sysUsers.setRealname(sysUser.getRealname());
        sysUsers.setPhone(sysUser.getUsername());
        sysUsers.setDelFlag(0);
        sysUsers.setId(sysUser.getId());
        sysUsers.setAvatar(sysUser.getAvatar());
        if(sysUser.getNickname()!=null && !"".equals(sysUser.getNickname())){
            sysUser.setNickname(sysUser.getNickname());
        }
        SysUser xmssSysUserEntity = sysUserService.getById(sysUsers.getId());
        if (xmssSysUserEntity == null) {
            return Result.error("未找到对应数据");
        }
        sysUserService.updateById(sysUsers);
        return Result.OK("编辑成功!");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "人大代表账号-通过id删除")
    @ApiOperation(value = "人大代表账号-通过id删除", notes = "人大代表账号-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        sysUserService.deleteUser(id);
        return Result.OK("删除成功!");
    }


    /**
     * 批量删除用户
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        baseCommonService.addLog("批量删除用户， ids： " + ids, CommonConstant.LOG_TYPE_2, 3);
        this.sysUserService.deleteBatchUsers(ids);
        return Result.ok("批量删除用户成功");
    }


    /**
     * 通过用户手机号查找是否重复
     *
     * @param
     * @param
     * @param
     * @param
     * @return
     */
    public List<SysUser> selectUser(@RequestParam(name = "name", required = false) String name, @RequestParam(name = "name", required = false) List<String> id) {

        SysUser sysUser = new SysUser();
        sysUser.setDelFlag(0);
        sysUser.setStatus(1);
        LoginUser sysUsers = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        sysUser.setCreateBy(sysUsers.getUsername());
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, null);
        List<SysUser> roles = sysUserRoleMapper.getRoleByUserNames(name, id);
        return roles;
    }


    /**
     * 列表查询
     *
     * @return
     */
    @AutoLog(value = "人大代表账号、督办账号-下拉列表查询")
    @ApiOperation(value = "人大代表账号、督办账号-下拉列表查询", notes = "人大代表账号、督办账号-下拉列表查询")
    @GetMapping(value = "/selectSysUser")
    public Result<?> selectSysUser(@RequestParam String thirdType) {
        LoginUser sysUsers = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysUser> getSysUser = sysUserRoleMapper.selectSysUser(sysUsers.getUsername(), sysUsers.getRelTenantIds() != null && !"".equals(sysUsers.getRelTenantIds()) ? sysUsers.getRelTenantIds() : null,thirdType);
        return Result.OK(getSysUser);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sysUser
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysUser sysUser, HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, request.getParameterMap());
        queryWrapper.select("username", "realname","avatar");
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-begin--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据--------------------
        String selections = request.getParameter("selections");
        if (!oConvertUtils.isEmpty(selections)) {
            queryWrapper.in("id", selections.split(","));
        }
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<SysUser> pageList = sysUserService.list(queryWrapper);

        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户列表");
        mv.addObject(NormalExcelConstants.CLASS, SysUser.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("用户列表数据", "导出人:" + user.getRealname(), "导出信息");
        exportParams.setImageBasePath(upLoadPath);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresRoles({"admin"})
    //@RequiresPermissions("user:import")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 错误信息
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SysUser> listSysUsers = ExcelImportUtil.importExcel(file.getInputStream(), SysUser.class, params);
                for (int i = 0; i < listSysUsers.size(); i++) {
                    SysUser sysUserExcel = listSysUsers.get(i);
                    if (StringUtils.isBlank(sysUserExcel.getPassword())) {
                        // 密码默认为 “123456”
                        sysUserExcel.setPassword("123456");
                    }
                    // 密码加密加盐
                    String salt = oConvertUtils.randomGen(8);
                    sysUserExcel.setSalt(salt);
                    String passwordEncode = PasswordUtil.encrypt(sysUserExcel.getUsername(), sysUserExcel.getPassword(), salt);
                    sysUserExcel.setPassword(passwordEncode);
                    try {
                        LoginUser sysUsers = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                        sysUserExcel.setRelTenantIds(sysUsers.getRelTenantIds());
                        sysUserExcel.setPhone(sysUserExcel.getUsername());
                        sysUserExcel.setCreateBy(sysUsers.getUsername());
                        sysUserExcel.setSalt(salt);
                        sysUserExcel.setDelFlag(0);
                        sysUserExcel.setStatus(1);
                        sysUserExcel.setActivitiSync(1);
                        sysUserService.save(sysUserExcel);
                        successLines++;
                    } catch (Exception e) {
                        errorLines++;
                        String message = e.getMessage();
                        int lineNumber = i + 1;
                        // 通过索引名判断出错信息
                        if (message.contains(CommonConstant.SQL_INDEX_SYS_USER_USERNAME)) {
                            errorMessage.add("第 " + lineNumber + " 行：登录名已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_USERNAME)) {
                            errorMessage.add("第 " + lineNumber + " 行：用户名已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_WORK_NO)) {
                            errorMessage.add("第 " + lineNumber + " 行：工号已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_PHONE)) {
                            errorMessage.add("第 " + lineNumber + " 行：手机号已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_EMAIL)) {
                            errorMessage.add("第 " + lineNumber + " 行：电子邮件已经存在，忽略导入。");
                        } else {
                            errorMessage.add("第 " + lineNumber + " 行：未知错误，忽略导入");
                            log.error(e.getMessage(), e);
                        }
                    }
                    // 批量将部门和用户信息建立关联关系
                 /*   String departIds = sysUserExcel.getDepartIds();
                    if (StringUtils.isNotBlank(departIds)) {
                        String userId = sysUserExcel.getId();
                        String[] departIdArray = departIds.split(",");
                        List<SysUserDepart> userDepartList = new ArrayList<>(departIdArray.length);
                        for (String departId : departIdArray) {
                            userDepartList.add(new SysUserDepart(userId, departId));
                        }
                        sysUserDepartService.saveBatch(userDepartList);
                    }*/

                }
            } catch (Exception e) {
                errorMessage.add("发生异常：" + e.getMessage());
                log.error(e.getMessage(), e);
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
    }


}
